<?php
/**
 * Slipstream :: Highly adaptive dependency injection framework
 * Copyright 2010-2011 Ian Unruh (Xerof3ar)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Slipstream\Infrastructure\Context\Relevance;

use ArrayObject;
use Slipstream\Configuration\ContextInterface;

/**
 *
 *
 * @author Ian Unruh (Xerof3ar) <ianunruh@gmail.com>
 * @since Class avaliable since release 1.0
 */
class CachedAnalyzerService extends AnalyzerService
{
	/**
	 * @var ArrayObject<string:ArrayObject<string:int>>
	 */
	protected $cachedWeights;
	
	/**
	 * Class constructor
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
		$this->cachedWeights = new ArrayObject();
	}
	
	/**
	 * Returns the relevance weight of a given context in terms of the target
	 * context
	 *
	 * @param ContextInterface $context
	 * @param ContextInterface $targetContext
	 * @return int
	 */
	public function getWeight(ContextInterface $context, ContextInterface $targetContext)
	{
		$cache = $this->getCacheForTargetContext($targetContext);
		
		$contextPath = $context->getPath();
		if(!$cache->offsetExists($contextPath)) {
			$cache->offsetSet($contextPath, parent::getWeight($context, $targetContext));
		}
		return $this->cache->offsetGet($contextPath);
	}
	
	/**
	 * Clears relevance weights from the cache
	 * @return void
	 */
	public function clearCache()
	{
		$this->cachedWeights = new ArrayObject();
	}
	
	protected function getCacheForTargetContext(ContextInterface $targetContext)
	{
		$path = $targetContext->getPath();
		
		$cache = $this->cachedWeights->offsetGet($path);
		if(is_null($cache)) {
			$cache = new ArrayObject();
			$this->cachedWeights->offsetSet($path, $cache);
		}
		return $cache;
	}
}